<template>
  <TodoHead></TodoHead>
  <TodoList></TodoList>
  <TodoFoot></TodoFoot>
</template>

<script setup>
import TodoHead from './components/TodoHead.vue';
import TodoList from './components/TodoList.vue';
import TodoFoot from './components/TodoFoot.vue';

import { ref, provide, computed } from 'vue';

let content = ref('');
let items = ref([]);

// 初始化 items，从 localStorage 读取待办事项并渲染 checked 状态
if (localStorage.length > 0) {
  Object.keys(localStorage).forEach(key => {
    const checked = localStorage.getItem(key) === 'true'; // 从 localStorage 读取 checked 状态
    items.value.push({
      key: key,
      checked: checked,
      isEditing: false, // 添加初始状态
      newKey: '', // 用于编辑的新值
    });
  });
  // 按 checked 状态排序，未完成的排在前面
  items.value.sort((a, b) => a.checked - b.checked);
}

// 添加待办事项
const handleAdd = () => {
  if (content.value.trim() === '') {
    alert('请输入有效内容');
    return;
  }

  // 检查是否已经存在相同的事项
  const existItem = items.value.find(item => item.key === content.value);
  if (existItem) {
    alert('该任务已经被添加了');
    return;
  }

  localStorage.setItem(content.value, false); // 新增的待办事项默认未选中
  items.value.push({
    key: content.value,
    checked: false,
    isEditing: false,
    newKey: '',
  });

  // 按 checked 状态排序
  items.value.sort((a, b) => a.checked - b.checked);

  // 清空输入框
  content.value = '';
};

// 删除待办事项
const handleDelete = index => {
  const itemKey = items.value[index].key;
  items.value.splice(index, 1);
  localStorage.removeItem(itemKey);
};

// 修改待办事项
const handleEdit = (index, newValue) => {
  const itemKey = items.value[index].key;
  if (newValue.trim() === '') {
    alert('请输入有效内容');
    return;
  }

  // 更新 items 和 localStorage
  items.value[index].key = newValue;
  localStorage.removeItem(itemKey); // 删除旧项
  localStorage.setItem(newValue, items.value[index].checked); // 添加新项
};

// 计算已办事项和总事项
const completedCount = computed(() => items.value.filter(item => item.checked).length);
const totalCount = computed(() => items.value.length);

// 清除已办
const handleClearCompleted = () => {
  items.value = items.value.filter(item => {
    if (item.checked) {
      localStorage.removeItem(item.key);
      return false; // 过滤掉已完成的项
    }
    return true; // 保留未完成的项
  });
};

// 清除所有
const handleClearAll = () => {
  items.value.forEach(item => localStorage.removeItem(item.key));
  items.value = [];
};

// 使用 provide 提供数据和操作函数
provide('content', content);
provide('items', items);
provide('handleAdd', handleAdd);
provide('handleDelete', handleDelete);
provide('handleEdit', handleEdit);

provide('completedCount', completedCount);
provide('totalCount', totalCount);
provide('handleClearCompleted', handleClearCompleted);
provide('handleClearAll', handleClearAll);
</script>

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
</style>
